<?php

class OrdersController extends AppController {

    var $name = 'Orders';
    var $components = array('WritingPad', 'UserAuthenticator');
    var $paginate = array(
        'fields' => array('Order.id', 'Order.created'),
        'limit' => 25,
        'order' => array(
            'Order.created' => 'asc'
        )
    );
    var $layout = 'layout_checkout';

    function view($id = null) {
        $this->layout = 'default';
        if (!$id) {
            $this->Session->setFlash(__('Invalid order', true));
            $this->redirect(array('action' => 'index'));
        }
        //$this->set('order', $this->Order->read(null, $id));

        $this->loadModel('OrderLineItem');

        $conditions = array("order_id" => $id,);
        $orderLineItems = $this->OrderLineItem->find('all',
                        array(
                            "conditions" => $conditions,
                            "recursive" => -1
                ));
//        debug($id);
//        debug($orderLineItems);
        $url = "menu_items/getUniqueOrderToken/";
        $order_token = $this->requestAction($url);
        $output = $this->WritingPad->getHumanReadableOrder($order_token);

        $orderLineItems = $this->getHumanReadableOrder($orderLineItems);
        $this->set(compact('orderLineItems', 'output', 'order_token'));
    }

    function getMenuItemDetails($menu_item_id) {
        $menu_item_details = $this->requestAction(
                        "/menu_items/getNameOfMenuItem/" . $menu_item_id);

        return $menu_item_details;
        //return $menu_item_details["MenuItem"]["item_name"];//$menu_item_id."_some_name";//$menu_item_details["item_name"];
    }

    /////to do
    function getHumanReadableOrder($orderLineItems) {
        //Order details stored in Session variable against unique $order_taken id
        //debug($order);
        $humanReadableOrder = array();
        foreach ($orderLineItems as $seq => $item) {

            $id = $item["OrderLineItem"]["menu_item_id"];
            $qty = $item["OrderLineItem"]["quantity"];
            $menu_item_details = $this->getMenuItemDetails($id);
            $humanReadableOrder[$id] = array(
                "menu_item_id" => $menu_item_details["MenuItem"]["id"],
                "menu_item_name" => $menu_item_details["MenuItem"]["item_name"],
                "quantity" => $qty,
                "price" => $menu_item_details["MenuItem"]["item_base_price"]
            );
        }

        //debug($humanReadableOrder);
        $temporarilyNotedOrder = $humanReadableOrder;
        return $temporarilyNotedOrder;
    }

    function createNewOrder($loggedInUserId) {
        if (!empty($this->data)) {
            debug($this->data);
            /**
             * Id of the user who is logged in. This will be stored against order in orders table.
             */
            $this->Order->createNewOrder($loggedInUserId);
        }
    }

    function add() {
        //debug($this->data);
        if (!empty($this->data)) {
            //Get the user id for whom we are creating a new order
            $loggedInUserId = $this->UserAuthenticator->getLoggedInUserId();

            //Create New Order in orders table
            $this->createNewOrder($loggedInUserId);

            //Get the id of the new order
            $orderId = $this->Order->id;
            //Get the order line items
            $orderLineItems = $this->data["Order"];

            /**
             * Prepare the orderToAdd array
             */
            $orderToAdd = array();
            $orderToAdd['orderId'] = $orderId;
            $orderToAdd['userId'] = $loggedInUserId;
            $orderToAdd['order_line_items'] = $orderLineItems;

            /**
             * Add the order_line_items in order_line_items table
             */
            //$this->requestAction("/order_line_items/addNewOrder/", array("pass"=>$orderToAdd));
            $this->requestAction(array('controller' => 'order_line_items', 'action' => 'addNewOrder'), array("pass" => array($orderToAdd)));

            /**
             * Start preparing the order.
             */
            $url = "/waiters/startPreparingTheORder/";
            $this->requestAction($url);

            /**
             * Since the order is placed, redirect the user to some other page.
             * Let say the menu card page.
             */
            $this->Session->setFlash("Order placed successfully... ");
            $url = "/menu_items/showmenu/";
            $this->redirect($url);
        } else {
            $vendorLocations = $this->Order->VendorLocation->find('list');
            $locations = $this->Order->Location->find('list');
            //$users = $this->Order->User->find('list');

            /**
             * OrderToken is the Unique Order Number that gets generated in Menu_Items_Controller.php
             */
            $uniqueOrderToken = $this->Session->read('OrderToken');
            $ordered_items_list = $this->WritingPad->getHumanReadableOrder($uniqueOrderToken);

            if (is_array($ordered_items_list) && count($ordered_items_list) > 0) {

                $this->set(compact('vendorLocations', 'locations', 'users', 'ordered_items_list'));
            } else {
                /**
                 * Since there is nothing in the order, redirect the user to some other page.
                 * Let say the menu card page.
                 */
                $this->Session->setFlash("Please choose delicious items from the menu!");
                $url = "/menu_items/showmenu/";
                $this->redirect($url);
                return;
            }
        }
    }

    function add_v2() {
        if (!empty($this->data)) {
            $this->Order->create();
            if ($this->Order->save($this->data)) {
                $this->Session->setFlash(__('The order has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The order could not be saved. Please, try again.', true));
            }
        }
        $vendorLocations = $this->Order->VendorLocation->find('list');
        $locations = $this->Order->Location->find('list');
        $users = $this->Order->User->find('list');
        $this->set(compact('vendorLocations', 'locations', 'users'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid order', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->Order->save($this->data)) {
                $this->Session->setFlash(__('The order has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The order could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Order->read(null, $id);
        }
        $vendorLocations = $this->Order->VendorLocation->find('list');
        $locations = $this->Order->Location->find('list');
        $users = $this->Order->User->find('list');
        $this->set(compact('vendorLocations', 'locations', 'users'));
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for order', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Order->delete($id)) {
            $this->Session->setFlash(__('Order deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Order was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    /**
     * This function displays all the orders placed by the logged in user.
     */
    function index($userId=null) {
        $this->layout = 'default';
        //if the argument is not provided , show the orders of the logged in user
        if ($userId == null || empty($userId)) {
            $userId = $this->UserAuthenticator->getLoggedInUserId();
        }
        $this->Order->recursive = 0;
        $conditions = array("user_id" => $userId);

        $this->Order->find('all', array("conditions" => $conditions));



        $orders = $this->paginate = array(
            'conditions' => array("Order.user_id" => $userId),
            'fields' => array('Order.id', 'Order.created', 'order_status', 'order_due_datetime', 'order_type'),
            'limit' => 25,
            'order' => array(
                'Order.created' => 'asc'
            )
        );

        $url = "menu_items/getUniqueOrderToken/";
        $order_token = $this->requestAction($url);
        $output = $this->WritingPad->getHumanReadableOrder($order_token);

        $this->set('orders', $this->paginate());
        $this->set('output', $output);
        $this->set('order_token', $order_token);

    }

    function showOrders() {
        $this->Order->recursive = 0;
        $this->set('orders', $this->paginate());
    }

}

?>